# _*_ coding: cp1252 _*_
#!/usr/bin/env python

# ...
import sys, os
#import pygame
import math
import time
import threading

# Aus Portabilitaetsgruenden. Haengt das Arbeitsverzeichnis vor den Dateinamen
def addWorkPath(filename):
	return os.path.join(os.path.dirname(sys.argv[0]), 'data', filename)


class GameLogic(threading.Thread):
	def __init__(self, race):
		threading.Thread.__init__(self)
		self.race	= race
		self.stoped	= threading.Event()
	
	def run(self):
		rot_speed = 0.1
		for kart in self.race.players[1:]:
			#kart.x_speed += 0.2
			kart.y_speed = 2
		while not self.stoped.isSet():
			kart = self.race.players[0]
			if self.race.controll_keys['key_left']:
				if kart.angle - rot_speed < 0:
					kart.angle = 2 * math.pi - rot_speed
				else:
					kart.angle -= rot_speed
			elif self.race.controll_keys['key_right']:
				if kart.angle + rot_speed > 2 * math.pi:
					kart.angle = (kart.angle + rot_speed) - 2 * math.pi
				kart.angle += rot_speed
			if self.race.controll_keys['key_up']:
				speed = math.sqrt(kart.x_speed ** 2 + kart.y_speed ** 2)
				if speed < 255:
					speed += 1.8
					kart.x_speed = math.sin(kart.angle) * speed
					kart.y_speed = math.cos(kart.angle) * speed
			elif self.race.controll_keys['key_down']:
				speed = math.sqrt(kart.x_speed ** 2 + kart.y_speed ** 2)
				if speed > -255:
					speed -= 1.8
					kart.x_speed = math.sin(kart.angle) * speed
					kart.y_speed = math.cos(kart.angle) * speed
			elif self.race.controll_keys['key_down']:
				pass
			kart.recalculatePosition()
			
			for kart in self.race.players[1:]:
				kart.angle += 0.02
				kart.recalculatePosition()
			time.sleep(0.1)


class Network(threading.Thread):
	def __init__(self, race):
		threading.Thread.__init__(self)
	
	def run(self):
		pass


class Player(object):
	def __init__(self, race, number):
		self.name		= 'Jannik'
		self.ip			= '0.0.0.128'
		self.number		= number
		self.rounds		= 0
		self.points		= 0
		self.item		= None
		
		self.x_pos, self.y_pos		= 64.0 + number * 10, 100.0
		self.x_speed, self.y_speed	= 0.0, 0.0
		self.angle					= 0.0
		#self.boosting				= False
		#self.breaking				= False
		
		self.pos_limit	= (race.track_map.map_size[0] * race.track_map.tile_size[0],
			race.track_map.map_size[1] * race.track_map.tile_size[1])
	
	def recalculatePosition(self):
		pass
		# Neuen Geschwindikeitsvektor aus dem Winkel berechnen
		speed = math.sqrt(self.x_speed ** 2 + self.y_speed ** 2)
		self.x_speed = -math.sin(self.angle) * speed
		self.y_speed = -math.cos(self.angle) * speed
		# Neue Position berechnen
		if self.x_pos + self.x_speed / 10 > self.pos_limit[0]:
			self.x_pos = 255
		elif self.x_pos + self.x_speed / 10 < 0:
			self.x_pos = 0
		else:
			self.x_pos += self.x_speed / 10
		
		if self.y_pos - self.y_speed / 10 > self.pos_limit[1]:
			self.y_pos = 255
		elif self.y_pos - self.y_speed / 10 < 0:
			self.y_pos = 0
		else:
			self.y_pos -= self.y_speed / 10		# Minus, wegen dem verdehten Koordiantensystem!
